package com.teamwork.module03.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.teamwork.common.entity.common.requestentity.ReqCommentBody;
import com.teamwork.common.entity.module03.Article;
import com.teamwork.common.entity.module03.dto.Comment2Dto;
import com.teamwork.module03.mapper.RtoRMapper;
import com.teamwork.module03.mapper.UserMapper;

import com.teamwork.module03.mapper.UserIconMapper;
import com.teamwork.common.entity.common.User;
import com.teamwork.common.entity.module03.Comment;
import com.teamwork.common.entity.module03.dto.CommentDto;
import com.teamwork.common.entity.module03.dto.ReplyDto;
import com.teamwork.common.result.Result;
import com.teamwork.module03.mapper.CommentMapper;
import com.teamwork.module03.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
 public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

     @Resource
     private UserMapper userMapper;
     @Resource
     private UserIconService userIconService;
     @Resource
     private ReplyService replyService;
     @Resource
     private ArticleService articleService;
     @Resource
     private CommentMapper commentMapper;
     @Resource
     @Lazy
     private UserService userService;
     @Resource
     private RtoRMapper rtoRMapper;

    /**
     * 根据文章id获取评论
     * @param id
     * @return
     */
    @Override
    public Result getCommentByAid(Long id) {

        LambdaQueryWrapper<Comment> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getArticleId,id).orderByDesc(Comment::getCreatetime);
        List<Comment> comlist = this.list(wrapper);
        //log.info("评论："+comlist);
        List<CommentDto> commentDtoList =new ArrayList<>();

        for(int i=0;i<comlist.size();i++){

            Long userId = comlist.get(i).getUserId();
            //查询用户图标
            String userIcon = userIconService.getByUserId(Math.toIntExact(userId)).getIcon();
            User user = userMapper.getById(userId);

           //String name = user.getUsername();
            //查询用户昵称
            String nickname = user.getNickname();

            List<ReplyDto> replyDtoList = replyService.listByComId(comlist.get(i).getId());

            CommentDto commentDto = new CommentDto(comlist.get(i),nickname,userIcon,replyDtoList);
            commentDtoList.add(commentDto);

        }


      // log.info("dto：{}",commentDtoList);
      //  System.out.println(comlist);
        return Result.success(commentDtoList);
    }

    @Override
    public Result getPage(Integer page, Integer size) {
        Page<Comment> pageinfo = new Page<>(page,size);

        this.page(pageinfo);

        return Result.success(pageinfo);
    }

    /**
     * 根据文章id删除评论。
     * @param artid 文章id
     * @return 返回是否删除
     */
    @Override
    public boolean deleteByArticleId(Long artid) {
        LambdaQueryWrapper<Comment> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getArticleId,artid);
        return this.remove(wrapper);
    }

    /**
     * 根据用户id删除评论
     * @param id 用户id
     * @return 是否删除
     */
    @Override
    public boolean deleteByUserId(Integer id) {
        LambdaQueryWrapper<Comment> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getUserId,id);
        boolean b = this.remove(wrapper);
        if(b) log.info("删除了用户id为:{} 发表的所有评论",id);
       // else log.error("删除了用户id为:{} 发表的所有评论出错！！！",id);
        return b;
    }

    @Override
    public Result toCommentByAId(int userid,int aid, String comment) {
        //想评论表插入一天数据

        String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());


        commentMapper.InsertCommentByAid(userid,aid,comment,nowtime);
       //在吧该文章的评论数加一
        articleService.addCommentCount(aid);

        return Result.success("评论成功！");
    }

    /**
     * 管理端评论的分页查询，可以按条件
     * @param reqCommentBody 请求实体
     * @return 评论内容
     */
    @Override
    public Result mangerPage(ReqCommentBody reqCommentBody) {
        //先建立分页
        Page<Comment> page = new Page<>(reqCommentBody.getPage(),reqCommentBody.getSize());
        //获取参数
        String username = reqCommentBody.getUsername();
        String nickname = reqCommentBody.getNickname();
        String title = reqCommentBody.getTitle();
        String content = reqCommentBody.getContent();

        if(username==null && nickname==null && title==null&& content==null){
            //都为空，则为正常查询
            this.page(page);
        }else if(username!=null && nickname==null && title==null&& content==null){
            //根据用户名查询
            LambdaQueryWrapper<User> wrapper =new LambdaQueryWrapper<>();
            wrapper.like(User::getUsername,username);
            List<Long> userids = userService.list(wrapper).stream().map(User::getId).collect(Collectors.toList());

            LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(Comment::getUserId,userids).orderByDesc(Comment::getCreatetime);
            this.page(page,queryWrapper);

        }else if(username==null && nickname!=null && title==null&& content==null ){
            //根据昵称查询
            LambdaQueryWrapper<User> wrapper =new LambdaQueryWrapper<>();
            wrapper.like(User::getNickname,nickname);
            List<Long> userids = userService.list(wrapper).stream().map(User::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(Comment::getUserId,userids).orderByDesc(Comment::getCreatetime);
            this.page(page,queryWrapper);
        }else if(username==null && nickname==null && title!=null&& content==null){
            //根据标题查询
            LambdaQueryWrapper<Article> wrapper=new LambdaQueryWrapper<>();
            wrapper.like(Article::getTitle,title);
            List<Long> artids = articleService.list(wrapper).stream().map(Article::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(Comment::getArticleId,artids).orderByDesc(Comment::getCreatetime);
            this.page(page,queryWrapper);
        }else if (username==null && nickname==null && title==null&& content!=null){
            //根据内容查询
            LambdaQueryWrapper<Comment> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.like(Comment::getComment,content).orderByDesc(Comment::getCreatetime);
            this.page(page,queryWrapper);
        }



        List<Comment2Dto> comment2DtoList = new ArrayList<>();

        //公共处理
        List<Comment> records = page.getRecords();
        for (Comment comment : records) {
            Long userId = comment.getUserId();
            User user = userService.getById(userId);
            String userUsername = user.getUsername();
            String userNickname = user.getNickname();

            String artitle = articleService.getById(comment.getArticleId()).getTitle();

            Comment2Dto comment2Dto = new Comment2Dto(comment, userUsername, userNickname,artitle);
            comment2DtoList.add(comment2Dto);
        }

        //装配
        Page<Comment2Dto> dtoPage = new Page<>();
        dtoPage.setRecords(comment2DtoList);
        BeanUtils.copyProperties(page,dtoPage,"records");

        return Result.success(dtoPage);
    }

    /**
     * 删除单个评论
     * @param cid
     * @return
     */
    @Override
    @Transactional
    public Result deleteOne(Integer cid) {
       //先查看该评论有没有回复
       replyService.delteByCid(cid);

        //再吧回复对回复里的都删除了
        rtoRMapper.deleteByCid(cid);

        //然后删除该条评论
        //吧对应文章的评论数减一
        Long aid = this.getById(cid).getArticleId();
        Article article = articleService.getById(aid);
        article.setComments(article.getComments()-1);
        boolean b1 = articleService.updateById(article);
        if(!b1){
            log.error("删除评论将对应文章id:{}评论数减一出错",aid);
            return Result.failure("删除失败！后台错误！");
        }

        boolean b = this.removeById(cid);
        if(!b){
            log.error("删除评论id:{}出错！！！",cid);
            return Result.failure("删除失败！，后台错误");
        }

        return Result.success("删除成功!");
    }

    /**
     * 批量删除评论
     * @param ids 评论id集合
     * @return 结果
     */
    @Override
    @Transactional
    public Result deleteBuch(List<Integer> ids) {
        for (Integer id : ids) {
            //先查看该评论有没有回复
            replyService.delteByCid(id);
            //再吧回复对回复里的都删除了
            rtoRMapper.deleteByCid(id);
            //将对应的文章评论都减一
            Long aid = this.getById(id).getArticleId();
            Article article = articleService.getById(aid);

            article.setComments(article.getComments()-1);
            boolean b = articleService.updateById(article);
            if(!b){
                log.error("批量删除批量时修改对应文章id:{}评论数出错！",aid);
                return Result.failure("删除失败！后台错误！");
            }
           //再继续删除所有评论
            boolean b1 = this.removeById(id);
            if(!b1) {
                log.error("批量删除评论出错对应评论id:{}", id);
                return Result.failure("删除失败！后台错误！");
            }


        }
        return Result.success("删除成功！");
    }
}
